package com.study.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.study.dto.UserDTO;
import com.study.exceptions.CourseException;
import com.study.exceptions.CourseSeckillException;
import com.study.exceptions.CourseSeckillOrderException;
import com.study.exceptions.UserException;
import com.study.seckill.dao.CourseSeckillMapper;
import com.study.seckill.dao.CourseSeckillOrderDao;
import com.study.seckill.dao.CourseSeckillOrderMapper;
import com.study.seckill.entity.CourseSeckill;
import com.study.seckill.entity.CourseSeckillOrder;
import com.study.seckill.service.CourseSeckillOrderService;
import com.study.seckill.service.CourseService;
import com.study.seckill.service.UserService;
import com.study.seckill.util.GenerateOrderNum;
import com.study.util.ResponseResult;
import com.study.vo.CourseInfoVO;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @ClassName: CourseSeckillOrderServiceImpl
 * @Author: wYin
 * @Date: 2022/3/10 14:44
 */
@Service
public class CourseSeckillOrderServiceImpl extends ServiceImpl<CourseSeckillOrderMapper, CourseSeckillOrder> implements CourseSeckillOrderService {

    @Autowired
    private UserService userService;

    @Autowired
    private CourseService courseService;

    @Autowired
    private CourseSeckillOrderMapper courseSeckillOrderMapper;

    @Autowired
    private CourseSeckillOrderDao courseSeckillOrderDao;


//    @Autowired
//    private CourseSeckillMapper seckillMapper;

    @Autowired
    private CourseSeckillMapper courseSeckillMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Override
    public CourseSeckillOrder addOrder(CourseSeckillOrder courseSeckillOrder, Integer userId) {
        //有效性校验
        ResponseResult<UserDTO> userInfo = userService.getById(userId);
        if(userInfo.getCode()!=200){
            throw new UserException("当前用户不合法");
        }
        Integer seckillId = courseSeckillOrder.getSeckillId();//秒杀id
        CourseSeckill courseSeckill = courseSeckillMapper.selectById(seckillId);//秒杀课程信息
        ResponseResult<CourseInfoVO> course = courseService.getById(courseSeckill.getCourseId());//查询课程信息
        if(course.getCode()!=200){
            throw new CourseException("当前课程不存在");
        }
        //判断当前秒杀课程是否属于有效时间--单一
        CourseSeckill courseSeckill1 = courseSeckillMapper.getCourseSeckill(seckillId);
        if(courseSeckill1==null){
            throw new CourseException("当前时间没有该秒杀课程");
        }
        courseSeckillOrder.setOrderNumber(orderNumber());
        courseSeckillOrder.setUserId(userId.toString());
        SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        courseSeckillOrder.setOrderTime(sim.format(new Date()));
        courseSeckillOrder.setOrderStatus("n");
        //添加订单
        CourseSeckillOrder save = courseSeckillOrderDao.save(courseSeckillOrder);
        if(save==null){
            return null;//更新失败
        }
        //发送订单信息
        rabbitTemplate.convertAndSend("wYin-letter-exchange","",save);
        // 修改课程的购买量+1
        rabbitTemplate.convertAndSend("wYin-updateBuyCount_exchange","",courseSeckill.getCourseId());
//        ResponseResult<Void> voidResponseResult = courseService.updateById(courseSeckill.getCourseId());
        //设置订单延迟队列，完成对订单到时未支付撤销的设置
        rabbitTemplate.convertAndSend("wYin-orderPayCheck-exchange","",save);
        return save;
    }

    @Override
    public Boolean updateOrderStatus(CourseSeckillOrder courseSeckillOrder, Integer userId) {
        //有效性校验
        if (userId.compareTo(Integer.valueOf(courseSeckillOrder.getUserId()))!=0) {
            throw new UserException("当前用户与课程用户信息不匹配");
        }
        ResponseResult<UserDTO> byId = userService.getById(userId);
        if(byId.getCode()!=200){
            throw new UserException("当前用户不存在");
        }
        //订单编号校验
        CourseSeckillOrder order  = courseSeckillOrderMapper.selectOne(new QueryWrapper<CourseSeckillOrder>().eq("order_number",
                courseSeckillOrder.getOrderNumber()));
        if(order==null){
            throw new CourseSeckillOrderException("没有查询到当前订单的信息");
        }
        //判断当前秒杀余量
        CourseSeckill courseSeckill1 = courseSeckillMapper.selectById(order.getSeckillId());
        if(courseSeckill1.getSeckillNum()<=0){
            throw new CourseSeckillException("当前秒杀课程已卖完");
        }

        //修改订单状态
        boolean result = courseSeckillOrderMapper.updateOrderStatus(courseSeckillOrder);
        if(result){
            CourseSeckill courseSeckill = courseSeckillMapper.selectById(courseSeckillOrder.getSeckillId());
            boolean b = courseSeckillMapper.updateSeckillStock(courseSeckillOrder.getSeckillId(), courseSeckill.getVersion());
            if(b){
                //更新版本
                courseSeckillMapper.updateSeckillVersion(courseSeckillOrder.getSeckillId(),
                        String.valueOf(new Date().getTime()));
                return true;
            }
        }
        return false;
    }

    @Override
    public void test() {
        rabbitTemplate.convertAndSend("wYin-letter-exchange","","测试");
    }

    @Override
    public CourseSeckillOrder findByOrderNumber(String orderNumber) {
        CourseSeckillOrder byOrderNumber = courseSeckillOrderDao.findByOrderNumber(orderNumber);
        if(byOrderNumber==null) {
            return null;
        }
        return byOrderNumber;
    }

    public String orderNumber(){
        String orderNum = GenerateOrderNum.getOrderNum();
        CourseSeckillOrder byOrderNumber = courseSeckillOrderDao.findByOrderNumber(orderNum);
        if(byOrderNumber!=null){
            orderNumber();
        }
        return orderNum;
    }
}
